import random
import pymysql
from flask import Flask, render_template
from flask_socketio import SocketIO
from kafka import KafkaConsumer

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
bootstrap_servers = "192.168.29.115:9092"
consumer = KafkaConsumer(
    auto_offset_reset='latest',
    bootstrap_servers=bootstrap_servers,
    group_id=str(random.randint(1, 99999999)),
)
consumer.subscribe(["result", "result1", "result2"])


def task():
    for data in consumer:
        if data.topic == "result":
            datas = data.value.decode('utf-8').split(' ')
            task1 = {
                datas[0]: datas[1],
                datas[2]: datas[3]
            }
            socketio.emit("task1", task1)
        if data.topic == "result1":
            datas = {}
            data_value = data.value.decode('utf8').split(" ")
            for messages in data_value:
                if messages:
                    datas[messages.split(":")[0]] = messages.split(":")[1]
            socketio.emit("task2", datas)
        if data.topic == "result2":
            datas1 = {}
            data_value = data.value.decode('utf8').split(" ")
            for messages in data_value:
                if messages:
                    datas1[messages.split(":")[0]] = messages.split(":")[1]
            socketio.emit("task3", datas1)


@app.route("/data1")
def get_data1():
    # 设置数据库连接信息
    host = 'localhost'
    port = 3306  # 替换为你的数据库端口号
    user = 'root'
    password = '123456'
    database = 'studentInfo'
    # 创建数据库连接
    conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
    # 创建游标
    cursor = conn.cursor()
    sql = "select *from student1 ORDER BY semester;"
    cursor.execute(sql)

    results = cursor.fetchall()
    xAxis = []
    datas = []
    for result in results:
        semester, class_id, gender, count = result
        xAxis.append(f'({semester},{class_id},{gender})')
        datas.append(f'{count}')

    # 关闭游标和连接
    cursor.close()
    conn.close()
    return {
        "xAxis": xAxis,
        "datas": datas
    }


@app.route("/data")
def get_data():
    host = 'localhost'
    port = 3306  # 替换为你的数据库端口号
    user = 'root'
    password = '123456'
    database = 'studentInfo'
    # 创建数据库连接
    conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
    # 创建游标
    cursor = conn.cursor()
    sql = "SELECT * FROM student;"
    cursor.execute(sql)
    results = cursor.fetchall()

    datas = []
    for result in results:
        class_id, gender, count = result
        gender = "男" if gender == 1 else "女"
        datas.append({
            "value": count,
            "name": str((class_id + "班", gender))
        })
    # 关闭游标和连接
    cursor.close()
    conn.close()
    return datas


@app.route("/")
def handle_mes():
    return render_template("index.html")


if __name__ == '__main__':
    socketio.start_background_task(task)
    socketio.run(app, host='127.0.0.1', port=5000, allow_unsafe_werkzeug=True, debug=True)
